import Taro from '@tarojs/taro'

export const config = {
  baseUrl: 'https://evaluation.rceid.com', // 生产
  // baseUrl: "http://5aa6fe7.r8.cpolar.top", // dev
  timeout: 6000
}

const interceptor = chain => {
  const requestParams = chain.requestParams
  const { header, data } = requestParams
  const headers = {
    ...header
  }
  const datas = {
    ...data
  }

  const classRes: API.ClassAdminItem = Taro.getStorageSync('CLASSRES')
  if (Object.keys(classRes).length > 0) {
    datas.classId = classRes.classId
  }

  const token = Taro.getStorageSync('TOKEN')
  if (token) headers.token = token

  requestParams.header = headers
  requestParams.data = datas

  return chain.proceed(requestParams).then(response => {
    return response
  })
}

Taro.addInterceptor(interceptor)

interface HttpsRequest {
  <T = any>(
    url: string,
    data?: any,
    method?: string,
    options?: any,
    getResponse?: boolean,
    skipErrorHandler?: boolean
  ): Promise<T>
}

const request: HttpsRequest = (
  url: string,
  params = {},
  method = 'GET',
  options = {},
  skipErrorHandler: boolean = false
) => {
  return new Promise((resolve, reject) => {
    Taro.request({
      ...options,
      method: method,
      url: `${config.baseUrl}/api${url}`,
      data: params
    })
      .then(({ statusCode, data, cookies = [] }) => {
        if (cookies.length > 0) {
          Taro.setStorageSync('cookies', cookies[0])
        }
        if (skipErrorHandler) {
          resolve(data)
          return
        }
        const { code, data: resultData } = data
        if (statusCode === 200 && code === 200) {
          resolve(resultData)
        } else if (code === 301) {
          Taro.showToast({
            icon: 'none',
            title: '请登录!',
            success: () => {
              Taro.removeStorageSync('TOKEN')
              Taro.removeStorageSync('USERINFO')
              setTimeout(() => {
                const router = Taro.getCurrentPages()
                if (
                  router?.[router.length - 1]?.route !== 'pages/index/index'
                ) {
                  Taro.navigateTo({
                    url: `/pages/index/index`
                  })
                }
              }, 1500)
            }
          })
          reject(data)
        } else {
          reject(data)
          throw new Error(data.msg || data.message || '网络请求错误!')
        }
      })
      .catch(err => {
        Taro.showToast({
          icon: 'none',
          title: err.message || err.errMsg || '网络请求错误!'
        })
        reject(err)
      })
  })
}

export default request
